﻿using FineUIPro;
using MyDataProcess;
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace KPI_SYSTEM.DictPage
{
    public partial class System_Dict : PageBase
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            if (Session["UserID"] == null)
            {
                Response.Redirect("../login.aspx");
            }
            if (!IsPostBack)
            {
                BindGridLeft();
            }
        }

        #region 左侧列表相关事件及方法
        // 删除左侧列表数据
        protected void btnLeftDelete_Click(object sender, EventArgs e)
        {
            if (GridLeft.SelectedRowIndexArray.Length > 0)
            {
                int rowID = Convert.ToInt32(GridLeft.DataKeys[GridLeft.SelectedRowIndexArray[0]][0]);
                DataTable dataTable = SqlHelper.ExecuteDataset(CommandType.Text, "SELECT * FROM SYSTEM_DICT WHERE PARENT_ID=" + rowID).Tables[0];
                if (dataTable.Rows.Count <= 0)
                {
                    DeleteRowByID(rowID);
                    BindGridLeft();
                    ShowNotify("删除数据成功!");
                }
                else
                {
                    ShowNotify("请先删除下级护理项目!");
                }
            }

        }




        protected void btnLeftSave_Click(object sender, EventArgs e)
        {
            try
            {
                String sqlInsert = "INSERT INTO SYSTEM_DICT (DICT_NAME,PARENT_ID) VALUES ('{0}','{1}')";
                String dictName = txtFormDICT_NAME.Text.Trim();
                String sql = String.Format(sqlInsert, dictName, "0");
                SqlHelper.ExecuteNonQuery(CommandType.Text, sql);
                ShowNotify("保存成功!");
                // 重新绑定表格，并点击当前编辑或者新增的行
                BindGridLeft();
                PageContext.RegisterStartupScript(String.Format("F('{0}').selectRow('{1}');", GridLeft.ClientID, "1") + WindowsLeft.GetHideReference());
            }
            catch (Exception ex)
            {

                throw new Exception("保存失败！");
            }

        }
        protected void GridLeft_RowSelect(object sender, GridRowSelectEventArgs e)
        {
            BindGridRight();
        }
        /// <summary>
        /// 根据科室CODE获取左侧项目列表
        /// </summary>
        /// <returns>返回PARENT_ID为0的根节点</returns>
        private DataTable GetSourceDataLeft()
        {
            DataTable dataTable = SqlHelper.ExecuteDataset(CommandType.Text, "SELECT * FROM SYSTEM_DICT WHERE  PARENT_ID=0").Tables[0];
            return dataTable;
        }
        /// <summary>
        /// 绑定左侧列表
        /// </summary>
        private void BindGridLeft()
        {
            DataTable table = GetSourceDataLeft();
            GridLeft.DataSource = table;
            GridLeft.DataBind();
        }
        #endregion


        #region 右上侧列表及相关事件
        /// <summary>
        /// 根据科室CODE获取左侧项目列表
        /// </summary>
        /// <returns>返回PATIENT_ID为0的根节点</returns>
        private DataTable GetSourceDataRight(String patientId)
        {
            String sql = "SELECT * FROM SYSTEM_DICT WHERE  PARENT_ID=" + patientId;
            DataTable dataTable = SqlHelper.ExecuteDataset(CommandType.Text, sql).Tables[0];
            return dataTable;
        }
        /// <summary>
        /// 绑定左侧列表
        /// </summary>
        private void BindGridRight()
        {
            String patientId = GridLeft.DataKeys[GridLeft.SelectedRowIndex][0].ToString();
            DataTable table = GetSourceDataRight(patientId);
            GridRight.DataSource = table;
            GridRight.DataBind();
        }
        // 删除左侧列表数据
        protected void btnRightDelete_Click(object sender, EventArgs e)
        {
            if (GridRight.SelectedRowIndexArray.Length > 0)
            {
                int rowID = Convert.ToInt32(GridRight.DataKeys[GridRight.SelectedRowIndexArray[0]][0]);
                DeleteRowByID(rowID);
                BindGridRight();
                ShowNotify("删除数据成功!");
            }

        }
        protected void btnRightSave_Click(object sender, EventArgs e)
        {
            try
            {
                SqlConnection conn = new SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings["SQL_Server"].ConnectionString);
                DataProcess dp = new DataProcess();
                DataSet ds = new DataSet();//创建dataset
                String strRowID = hfFormIDRight.Text;
                String dictName = txtRightDICT_NAME.Text.Trim();
                String dictValue = txtRightDICT_VALUE.Text.Trim();
                String dictRemark = txtRightDICT_REMARK.Text.Trim();
                if (String.IsNullOrEmpty(strRowID))
                {
                    String sqlInsert = "INSERT INTO SYSTEM_DICT (DICT_NAME,DICT_VALUE,PARENT_ID,DICT_REMARK) VALUES ('{0}','{1}','{2}','{3}')";
                    String patientId = GridLeft.DataKeys[GridLeft.SelectedRowIndex][0].ToString();
                    String sql = String.Format(sqlInsert, dictName, dictValue, patientId, dictRemark);
                    SqlHelper.ExecuteNonQuery(CommandType.Text, sql);
                    ShowNotify("保存成功!");
                }
                else
                {
                    // 编辑
                    int rowID = Convert.ToInt32(strRowID);
                    string sql = "SELECT * FROM SYSTEM_DICT WHERE REC_ID=" + rowID;
                    SqlDataAdapter dataAdapter = new SqlDataAdapter(sql, conn);//创建dataadapter
                    SqlCommandBuilder cb = new SqlCommandBuilder(dataAdapter);//使用oraclecommand类和dataadapter类对数据库操作
                    dataAdapter.Fill(ds, "serverInfo");
                    DataTable table = ds.Tables[0];
                    DataRow currRow = table.Rows[0];

                    currRow["REC_ID"] = rowID;
                    currRow["DICT_NAME"] = dictName;
                    currRow["DICT_VALUE"] = dictValue;
                    currRow["DICT_REMARK"] = dictRemark;
                    dataAdapter.Update(table.GetChanges());
                    table.AcceptChanges();
                }
                // 重新绑定表格，并点击当前编辑或者新增的行
                BindGridRight();
                PageContext.RegisterStartupScript(String.Format("F('{0}').selectRow('{1}');", GridRight.ClientID, "1") + WindowsRight.GetHideReference());
            }
            catch (Exception ex)
            {

                throw new Exception("保存失败！");
            }

        }
        protected void GridRight_RowCommand(object sender, GridCommandEventArgs e)
        {
            if (e.CommandName == "Delete")
            {
                int rowID = Convert.ToInt32(GridRight.DataKeys[e.RowIndex][0]);
                try
                {
                    DeleteRowByID(rowID);
                    BindGridRight();
                    ShowNotify("删除数据成功!");

                }
                catch (Exception ex)
                {
                    ShowNotify("删除数据失败!");
                }
            }
        }
        protected void GridRight_PreRowDataBound(object sender, GridPreRowEventArgs e)
        {
            // 如果绑定到 DataTable，那么这里的 DataItem 就是 DataRowView
            DataRowView row = e.DataItem as DataRowView;
            int rowId = Convert.ToInt32(row["REC_ID"]);

            LinkButtonField editField = GridRight.FindColumn("Edit") as LinkButtonField;
            editField.OnClientClick = String.Format("showEditWindow('{0}');", rowId);
        }
        #endregion

        // 根据行ID来删除行数据
        private void DeleteRowByID(int rowID)
        {
            try
            {
                SqlHelper.ExecuteNonQuery(CommandType.Text, "DELETE FROM SYSTEM_DICT WHERE REC_ID=" + rowID);
            }
            catch (Exception ex)
            {
                throw new Exception("删除失败！");
            }
        }
    }

}